<template>

    <view class="page-room">
        <view v-if="0" class="" style="background-color: #FFFFFF;width: 200rpx;height: 400rpx;">
            <button type="default" style="font-size: 16px;"
                @click="_pusherAudioHandler">{{pusher.enableMic?'开启麦克风':'关闭麦克风'}}</button>

            <view v-for="(item,index) in userStatusList" class="" :key="index">
                {{index}}: {{item.enableMic?'开':'关'}}
            </view>
        </view>

        <view class="tip-toast" v-if="showTipToast">
            <view>VR带看</view>
            <view>对方忙线中，请稍后再试</view>
        </view>
        <web-view v-else :src="webUrl"></web-view>
        <!-- template custom -->
        <template v-if="shopInfo.audioType!=1">
            <view class="template-custom" style="opacity: 0;">
                <view class="players-container">
                    <view v-if="item.src && (item.hasVideo || item.hasAudio)"
                        :class="'view-container player-container ' + (item.isVisible ? '' : 'none')"
                        :style="'left:' + item.xAxis + ';top:' + item.yAxis + ';width:' + item.width + ';height:' + item.height + ';z-index:' + item.zIndex + ';'"
                        v-for="(item, index) in playerList" :key="item.streamID">
                        <live-player class="player" :id="item.streamID" :data-userid="item.userID"
                            :data-streamid="item.streamID" :data-streamtype="item.streamType" :src="item.src"
                            :mode="item.mode" :autoplay="item.autoplay" :mute-audio="item.muteAudio"
                            :mute-video="item.muteVideo" :orientation="item.orientation" :object-fit="item.objectFit"
                            :background-mute="item.enableBackgroundMute" :min-cache="item.minCache"
                            :max-cache="item.maxCache" :sound-mode="item.soundMode"
                            :enable-recv-message="item.enableRecvMessage" :auto-pause-if-navigate="item.autoPauseIfNavigate"
                            :auto-pause-if-open-native="item.autoPauseIfOpenNative" :debug="debug"
                            @statechange="_playerStateChange" @fullscreenchange="_playerFullscreenChange"
                            @netstatus="_playerNetStatus" @audiovolumenotify="_playerAudioVolumeNotify" />
                    </view>
                </view>
                <view :class="'view-container pusher-container ' + (pusher.isVisible ? '' : 'none')"
                    :style="'left:' + pusher.xAxis + ';top:' + pusher.yAxis + ';width:' + pusher.width + ';height:' + pusher.height + ';z-index:' + pusher.zIndex + ';'">
                    <live-pusher class="pusher" :url="pusher.url" :mode="pusher.mode" :autopush="pusher.autopush"
                        :enable-camera="pusher.enableCamera" :enable-mic="pusher.enableMic" :muted="!pusher.enableMic"
                        :enable-agc="pusher.enableAgc" :enable-ans="pusher.enableAns"
                        :enable-ear-monitor="pusher.enableEarMonitor" :auto-focus="pusher.enableAutoFocus"
                        :zoom="pusher.enableZoom" :min-bitrate="pusher.minBitrate" :max-bitrate="pusher.maxBitrate"
                        :video-width="pusher.videoWidth" :video-height="pusher.videoHeight" :beauty="pusher.beautyLevel"
                        :whiteness="pusher.whitenessLevel" :orientation="pusher.videoOrientation"
                        :aspect="pusher.videoAspect" :device-position="pusher.frontCamera"
                        :remote-mirror="pusher.enableRemoteMirror" :local-mirror="pusher.localMirror"
                        :background-mute="pusher.enableBackgroundMute" :audio-quality="pusher.audioQuality"
                        :audio-volume-type="pusher.audioVolumeType" :audio-reverb-type="pusher.audioReverbType"
                        :waiting-image="pusher.waitingImage" :debug="debug" @statechange="_pusherStateChangeHandler"
                        @netstatus="_pusherNetStatusHandler" @error="_pusherErrorHandler" @bgmstart="_pusherBGMStartHandler"
                        @bgmprogress="_pusherBGMProgressHandler" @bgmcomplete="_pusherBGMCompleteHandler"
                        @audiovolumenotify="_pusherAudioVolumeNotify" />
                </view>
            </view>
        </template>

    </view>

</template>

<script>
    import TRTC from '../static/trtc-wx';
    import {
        mapState,
        mapMutations,
        mapActions
    } from 'vuex';
    const Config = require("@/config.js");
    const api = require("@/static/js/api.js");
    const Signature = {};

    const utils = require("@/static/js/utils.js")
    import wsRequest from '../static/websocket.js'
    let websocket = null
    let that = null
    let txTimerId = null
    export default {
        data() {
            return {
                roomID: 0,

                // 房间号
                role: 'presenter',

                initialRole: '',
                showRolePanel: false,
                userID: '',
                options: {

                },
                _rtcConfig: {
                    sdkAppID: '',
                    // 必要参数 开通实时音视频服务创建应用后分配的 sdkAppID
                    userID: '',
                    // 必要参数 用户 ID 可以由您的帐号系统指定
                    userSig: '' // 必要参数 身份签名，相当于登录密码的作用
                },

                pusher: null,
                playerList: [], //=== 有
                userList: [], //=== 加入房间的所有玩家
                userStatusList: [],
                enableMic: true,
                headerHeight: '',
                statusBarHeight: '',
                debug: '',

                webUrl: '',
                showTipToast: false,

            };
        },
        computed: {
            ...mapState({
                hasLogin: state => state.userInfo.hasLogin,
                isAuthPhone: state => state.userInfo.isAuthPhone,
                isAuthUserInfo: state => state.userInfo.isAuthUserInfo,
                isSeller: state => state.userInfo.isSeller,
                sellerObj: state => state.userInfo.sellerObj,
                buyerObj: state => state.userInfo.buyerObj,
                shopInfo: state => state.userInfo.shopInfo,
            }),
        },

        /**
         * 生命周期函数--监听页面加载
         */
        onLoad(options) {
            let that = this
            console.log('room onload', options);
            uni.setKeepScreenOn({
                keepScreenOn: true
            });
            websocket = new wsRequest(Config.service.roomWebSocketUrl + '/' + options.userID + 'MiniApp', 5000, options
                .userID)
            websocket.addOnMsg('chatRoom', this.onMessage)

            var paramObj = {
                userId: options.userID,
                ownerId: options.ownerId,
                roomId: options.roomID,
                ifhd: this.shopInfo.audioType==1?2:1, //是否带看
                // ifctrl: options.isSeller == 1 ? 1 : 2, //1是置业顾问 2顾客
            }
            // that.webUrl ="https://talkyi.fzzkzh.com/rtc-test/index.html#/?pid=1000" + '&' + utils.KeyValueToUrl(paramObj)
            that.webUrl = that.shopInfo.panoramaUrl + '&' + utils.KeyValueToUrl(paramObj)

            console.log("webRoom webviewUrl:", that.webUrl)

            if (this.shopInfo.audioType != 1){
                this.TRTC = new TRTC(this);
                
                this.init(options);
                this.bindTRTCRoomEvent();
                
                // 将String 类型的 true false 转换成 boolean
                Object.getOwnPropertyNames(options).forEach(key => {
                    if (options[key] === 'true') {
                        options[key] = true;
                    }
                
                    if (options[key] === 'false') {
                        options[key] = false;
                    }
                });
                
                this.options = options; // querystring 只支持传递 String 类型, 注意类型转换
                
                this.enterRoom({
                    roomID: options.roomID
                });
                //====初始化，列表
                this.getUserInfoListByIds([])  
                 
                txTimerId = setInterval(() => {
                    that.sendUserList()
                }, 5000)
            }
             
        },
        onReady() {
            console.log('room ready');
        },
        onUnload() {
            clearInterval(txTimerId);
            this.exitRoom();
            websocket.close();
            websocket = null;

            console.log('room unload');
        },
        methods: {
            onMessage(obj) {
                if (obj.type == "chatRoom") {
                    console.log("chatRoom onMessage:", obj)

                    this.setPusherAttributesHandler({
                        enableMic: obj.message.enableMic //true
                    });
                }
            },
            sendUserList() {
                var playerList = this.playerList
                var userList = this.userList
                console.log("sendUserList", playerList, userList)
                this.userStatusList.splice(0, this.userStatusList.length);

                for (var i = 0; i < userList.length; i++) {
                    var userID = userList[i].userID
                    var obj = {
                        userID: userList[i].userID,
                        name: userList[i].name,
                        avatar: userList[i].avatar,
                        enableMic: false, //是否开启语音                  
                    }
                    //===本人状态，判断
                    if (userID == this.options.userID){
                        obj.enableMic = this.pusher.enableMic
                    }
                    //===其他人状态判断
                    for (var j = 0; j < playerList.length; j++) {
                        if (userID == playerList[j].userID) {
                            obj.enableMic = true;
                        }
                    }
                    this.userStatusList.push(obj)
                }


                if (this.options && this.options.userID && this.options.userID.length > 0) {
                    let data = {
                        from: this.options.userID + 'MiniApp',
                        to: this.options.userID + 'H5',
                        type: 'chatRoom',
                        room: {
                            roomId: '',
                            ownerId: '',
                        },
                        message: JSON.stringify(this.userStatusList),
                    }
                    console.log("send player list:", data);
                    websocket.send(JSON.stringify(data));
                }
            },

            getUserSigVideo(userId, success) {
                api.getImUserSign({
                    interfaceName: userId,
                    param: {}
                }).then(res => {
                    console.log('getUserSig', res);
                    if (res.success) {
                        Signature.userSig = res.data;
                        Signature.sdkAppID = Config.imSdkAppID;
                        typeof success == 'function' && success();
                    }
                })
            },

            init(options) {
                // pusher 初始化参数
                const pusherConfig = {
                    beautyLevel: 9,
                    audioVolumeType: 'media'
                };
                const pusher = this.TRTC.createPusher(pusherConfig);
                this.setData({
                    _rtcConfig: {
                        userID: options.userID,
                        sdkAppID: options.sdkAppID,
                        userSig: options.userSig
                    },
                    role: options.role,
                    initialRole: options.role,
                    roomID: options.roomID,
                    pusher: pusher.pusherAttributes
                });
            },

            enterRoom() {
                var options = this.options
                this.getUserSigVideo(options.userID, () => {
                    this.__enterRoom({
                        roomID: Number(options.roomID),
                        userID: options.userID,
                        template: options.template,
                        debugMode: options.debugMode,
                    });
                });
            },

            __enterRoom(params) {
                params.template = params.template || '1v1';
                params.roomID = params.roomID || this.randomroomID();
                params.userID = params.userID || this.randomUserID();
                console.log('* room enterRoom', params);
                params.sdkAppID = Signature.sdkAppID;
                params.userSig = Signature.userSig;
                this.template = params.template;

                this._rtcConfig = {
                    roomID: params.roomID,
                    sdkAppID: params.sdkAppID, // 您的实时音视频服务创建应用后分配的 sdkAppID
                    userID: params.userID,
                    userSig: params.userSig,
                    template: params.template, // 1v1 grid custom
                    debugMode: false, // 非必要参数，打开组件的调试模式，开发调试时建议设置为 true
                    audioVolumeType: 'voicecall',
                }

                this.setData({
                        pusher: this.TRTC.enterRoom(this._rtcConfig)
                    },
                    () => {
                        this.TRTC.getPusherInstance().start(); // 开始推流（autoPush的模式下不需要）
                    }
                );
            },

            exitRoom() {
                const result = this.TRTC.exitRoom();
                this.setData({
                    pusher: result.pusher,
                    playerList: result.playerList
                });

            },

            // 设置 pusher 属性
            setPusherAttributesHandler(options) {
                this.setData({
                    pusher: this.TRTC.setPusherAttributes(options)
                }, () => {
                    this.sendUserList()
                });
            },

            // 设置某个 player 属性
            setPlayerAttributesHandler(player, options) {
                var playerList = this.TRTC.setPlayerAttributes(player.streamID, options)
                this.playerList = playerList;
                this.sendUserList()
            },

            // 事件监听
            bindTRTCRoomEvent() {
                const TRTC_EVENT = this.TRTC.EVENT; // 初始化事件订阅

                this.TRTC.on(TRTC_EVENT.LOCAL_JOIN, (event) => {
                    console.log('* room LOCAL_JOIN', event); // 进房成功，触发该事件后可以对本地视频和音频进行设置

                    if (this.role === 'presenter') {
                        this.setPusherAttributesHandler({
                            enableMic: true
                        });
                    }
                });
                this.TRTC.on(TRTC_EVENT.LOCAL_LEAVE, (event) => {
                    console.log('* room LOCAL_LEAVE', event);
                });

                this.TRTC.on(TRTC_EVENT.ERROR, (event) => {
                    console.log('* room ERROR', event);
                });

                // 远端用户进房
                this.TRTC.on(TRTC_EVENT.REMOTE_USER_JOIN, event => {
                    console.log('* room REMOTE_USER_JOIN', event, this.TRTC)
  
                    this.getUserInfoListByIds(event.data.userList, ()=>{
                        this.sendUserList()
                    })                 
                });

                // 远端用户退出
                this.TRTC.on(TRTC_EVENT.REMOTE_USER_LEAVE, (event) => {
                    console.log('* room REMOTE_USER_LEAVE', event);
                    this.getUserInfoListByIds(event.data.userList, ()=>{
                        this.sendUserList()
                    }) 
                });

                // 远端用户推送音频
                this.TRTC.on(TRTC_EVENT.REMOTE_AUDIO_ADD, (event) => {
                    console.log('* room REMOTE_AUDIO_ADD', event);
                    const {
                        player
                    } = event.data;
                    this.setPlayerAttributesHandler(player, {
                        muteAudio: false
                    });
                }); // 远端用户取消推送音频

                this.TRTC.on(TRTC_EVENT.REMOTE_AUDIO_REMOVE, (event) => {
                    console.log('* room REMOTE_AUDIO_REMOVE', event);
                    const {
                        player
                    } = event.data;
                    this.setPlayerAttributesHandler(player, {
                        muteAudio: true
                    });
                });
            },

            getUserInfoListByIds(list, callback) {
                let that = this
                let ids = []
                
                ids.push(this.options.userID)
                for (var i = 0; i < list.length; i++) {
                    ids.push(list[i].userID)
                }
                
                api.getUserListByIds({
                    param: {
                        ids: ids,
                    }
                }).then(res => {
                    console.log(res)
                    if (res.success) {
                        that.userList.splice(0, that.userList.length)
                        for (var i=0; i<res.data.length ;i++){
                            var item = res.data[i]
                            var obj = {
                                userID: item.id,
                                name: item.name||'',
                                avatar: item.avatar||''
                            }
                            that.userList.push(obj)
                        }
                        typeof callback == 'function' && callback();
                    }
                })
            },

            _handleRoleChange() {
                if (this.initialRole !== 'presenter') {
                    this.setData({
                        showRolePanel: !this.showRolePanel
                    });
                }
            },

            // 是否订阅某一个player Audio
            _mutePlayerAudio(event) {
                const player = event.currentTarget.dataset.value;

                if (player.hasAudio && player.muteAudio) {
                    this.setPlayerAttributesHandler(player, {
                        muteAudio: false
                    });
                    return;
                }

                if (player.hasAudio && !player.muteAudio) {
                    this.setPlayerAttributesHandler(player, {
                        muteAudio: true
                    });
                    return;
                }
            },

            // 挂断退出房间
            _hangUp() {

                uni.navigateBack({
                    delta: 1
                });
            },

            // 关闭
            _allPlayerMuteAudio() {
                if (this.playerList.length === 0) {
                    return;
                }

                const players = this.TRTC.getPlayerList();
                const muteAudio = !this.muteAudio;

                if (muteAudio) {
                    uni.showToast({
                        title: '开启禁言',
                        icon: 'none',
                        duration: 2000
                    });
                } else {
                    uni.showToast({
                        title: '取消禁言',
                        icon: 'none',
                        duration: 2000
                    });
                }

                this.setData({
                    muteAudio: muteAudio
                });
                players.forEach((player) => {
                    this.setPlayerAttributesHandler(player, {
                        muteAudio: muteAudio
                    });
                });
            },

            _confirmRoleChange() {
                if (this.role === 'audience') {
                    this.setPusherAttributesHandler({
                        enableMic: true
                    });
                    this.setData({
                        role: 'presenter',
                        showRolePanel: false
                    });
                } else {
                    this.setPusherAttributesHandler({
                        enableMic: false
                    });
                    this.setData({
                        role: 'audience',
                        showRolePanel: false
                    });
                }
            },

            // 订阅 / 取消订阅 Audio
            _pusherAudioHandler() {
                if (this.pusher.enableMic) {
                    this.setPusherAttributesHandler({
                        enableMic: false
                    });
                } else {
                    this.setPusherAttributesHandler({
                        enableMic: true
                    });
                }
            },

            // 请保持跟 wxml 中绑定的事件名称一致
            _pusherStateChangeHandler(event) {
                this.TRTC.pusherEventHandler(event);
            },

            _pusherNetStatusHandler(event) {
                this.TRTC.pusherNetStatusHandler(event);
            },

            _pusherErrorHandler(event) {
                this.TRTC.pusherErrorHandler(event);
            },

            _pusherBGMStartHandler(event) {
                this.TRTC.pusherBGMStartHandler(event);
            },

            _pusherBGMProgressHandler(event) {
                this.TRTC.pusherBGMProgressHandler(event);
            },

            _pusherBGMCompleteHandler(event) {
                this.TRTC.pusherBGMCompleteHandler(event);
            },

            _pusherAudioVolumeNotify(event) {
                this.TRTC.pusherAudioVolumeNotify(event);
            },

            _playerStateChange(event) {
                this.TRTC.playerEventHandler(event);
            },

            _playerFullscreenChange(event) {
                this.TRTC.playerFullscreenChange(event);
            },

            _playerNetStatus(event) {
                this.TRTC.playerNetStatus(event);
            },

            _playerAudioVolumeNotify(event) {
                this.TRTC.playerAudioVolumeNotify(event);
            },

            onBack() {
                console.log('占位：函数 onBack 未声明');
            },
            randomUserID: function() {
                return new Date().getTime().toString(16).split('').reverse().join('');
            },
            randomroomID: function() {
                return parseInt(Math.random() * 9999);
            },
        }
    };
</script>
<style>
    /* miniprogram/pages/room/room.wxss */
    .page-room {
        width: 100vw;
        height: 100vh;
        overflow: hidden;
        background-image: url('https://mc.qcloudimg.com/static/img/7da57e0050d308e2e1b1e31afbc42929/bg.png');
        background-color: #333;
        background-repeat: no-repeat;
        background-size: cover;
    }

    .title {
        color: #ffffff;
        padding-top: 65rpx;
        line-height: 60rpx;
        text-align: center;
    }

    .page-room .avatar {
        height: 100rpx;
        width: 100rpx;
        border-radius: 50%;
        background: #999;
        overflow: hidden;
    }

    .user-container {
        box-sizing: border-box;
        padding: 80rpx 60rpx 0 60rpx;
        height: 900rpx;
        overflow: hidden;
        color: white;
    }

    .own {
        height: 180rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }

    .avatar-image {
        width: 100%;
        height: 100%;
    }

    .users {
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
        padding-top: 40rpx;
    }

    .user {
        height: 200rpx;
        width: 33.3%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        font-size: 24rpx;
    }

    .userID {
        padding-top: 20rpx;
    }

    .avatar-fake {
        height: 100rpx;
        width: 100rpx;
        border-radius: 50%;
        background: #999;
    }

    .bg {
        width: 100vw;
        height: 100vh;
    }

    .close {
        position: absolute;
        padding-left: 5vw;
        padding-right: 5vw;
        width: 50rpx;
        height: 60rpx;
    }

    .back {
        font-size: 32rpx;
        line-height: 32rpx;
        padding-left: 5vw;
        padding-right: 5vw;
        width: 50rpx;
    }

    .title {
        color: white;
        font-size: 32rpx;
        font-weight: 500;
    }

    .role-choose {
        position: absolute;
        width: 90vw;
        background: white;
        border: 1px solid #bfbfbf;
        border-radius: 12rpx;
        top: 40vh;
        left: 5vw;
        padding: 40rpx;
        box-sizing: border-box;
    }

    .role-panel-text {
        font-size: 32rpx;
        font-weight: 500;
    }

    .handle-btn {
        display: flex;
        flex-direction: row-reverse;
        margin-top: 20rpx;
    }

    .role-btn {
        margin-left: 20rpx;
        padding: 10rpx 20rpx;
        border-radius: 12rpx;
    }

    .confirm {
        background: #006eff;
        color: white;
    }

    .setting {
        height: 100%;
        padding: 100rpx 60rpx;
        display: flex;
        flex-direction: row;
        justify-content: space-around;
    }

    .btn-normal {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        background: white;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .btn-normal image {
        width: 50rpx;
        height: 50rpx;
    }

    .close {
        position: absolute;
        padding-left: 5vw;
        padding-right: 5vw;
        width: 50rpx;
        height: 60rpx;
    }

    /* 通过方法自定义模式 */
    .template-custom {
        /* 绝对定位模式 pusher 和 player 都用绝对定位*/
        width: 100vw;
        height: 100vh;
        position: relative;
    }

    .template-custom .pusher-container,
    .template-custom .player-container {
        position: absolute;
    }
</style>
